<template>
  <div class="main">
    <!-----------------Chart 容器--------------------->
    <div id="chart-view"></div>
    <!----------------Loading 容器-------------------->
    <v-loading :loadingShow="loading.show" :loadingText="loading.text"></v-loading>
    <!----------------数据详情面板-------------------->
    <div class="country-info" :v-model="countryData">
      <span class="country-name">{{ currentCountry.name }}</span>
      <span>感染人数：{{ currentCountry.confirmed }}</span>
      <span>死亡人数：{{ currentCountry.deaths }}</span>
      <span>康复人数：{{ currentCountry.recovered }}</span>
      <span>更新时间：{{ currentCountry.last_updated }}</span>
    </div>
  </div>
</template>

<script>
//引入世界地图geojson
import worldmap from "../assets/json/world.json"
export default {
  data() {
    return {
      //loading显示控制
      loading: {
        text: '正在向 herokuapp.com 请求数据...',
        show: true
      },
      //全球数据
      globalData: {},
      //各国家数据
      countryData: [],
      //当前国家数据
      currentCountry: {
        name: "",
        confirmed: "",
        deaths: "",
        recovered: "",
        last_updated: ""
      },
      //chart绑定数据
      chartData: [],
      //chart对象
      myChart: {},
      //chart设置项
      myChartOption: {
        //地图背景色
        backgroundColor: "rgba(0,0,0,0.8)",
        //悬浮框
        tooltip: {
          trigger: "item",
          showDelay: 0,
          transitionDuration: 0.2,
          formatter: (params) => {
            return (
              params.name +
              "<br/>" +
              params.seriesName +
              ": " +
              this.$utils.toThousands(params.value)
            )
          }
        },
        //视觉映射组件
        visualMap: {
          min: 0,
          max: 30000000,
          type: 'piecewise',
          splitNumber:9,
          pieces: [
              {min: 0, max: 1000, label: '一千人以内', color: '#FFFFBB'},
              {min: 1001, max: 10000, label: '一千至一万人', color: '#FFEE99'},
              {min: 10001, max: 50000, label: '一万至五万人', color: '#FFFF77'},
              {min: 50001, max: 100000, label: '五万至十万人', color: '#FFDD55'},
              {min: 100001, max: 500000, label: '十万至五十万人', color: '#FFBB66'},
              {min: 500001, max: 1000000, label: '五十万至一百万人', color: '#FFAA33'},
              {min: 1000001, max: 5000000, label: '一百万至五百万人', color: '#FF8800'},
              {min: 5000001, max: 10000000, label: '五百万至一千万人', color: '#FF5511'},
              {min: 10000001, label: '一千万人以上', color: '#FF0000'},
          ],
          right: 20,
          top: 'middle',
          calculable: true,
          textStyle: {
             color: '#fff'
          }
        },
        //数据系列
        series: [
          {
            name: "感染人数",
            nameProperty: "name",
            type: "map",
            roam: true,
            map: "world",
            itemStyle: {
              emphasis: {
                areaColor: "#1E90FF",
                borderColor: "#0000FF"
              }
            },
            select: {
              itemStyle: {
                areaColor: "#1E90FF",
                borderColor: "#0000FF"
              }
            },
            emphasis: {
              label: {
                show: true
              }
            },
            // 文本位置修正
            textFixed: {
              Alaska: [20, -20]
            },
            data: []
          }
        ]
      }
    }
  },
  created() {
    //初始化加载数据
    this.getGlobalData()
  },
  methods: {
    //异步请求数据
    async getGlobalData() {
      this.$api.world.getWorldData().then( res => {
        if (res.status !== 200) return this.loading.text = 'herokuapp.com api 不稳定，请刷新再试' 
        this.globalData = res.data.latest
        var flag = false
        res.data.locations.forEach((r) => {
            this.countryData.forEach((c) => {
            if (r.country === c.country) {
                c.latest.confirmed = c.latest.confirmed + r.latest.confirmed
                c.latest.deaths = c.latest.deaths + r.latest.deaths
                c.latest.recovered = c.latest.recovered + r.latest.recovered
                flag = true
            }
            })
            if (!flag) this.countryData.push(r)
            flag = false
        })
        this.countryData.forEach((c) => {
            if (c.country === "Bosnia and Herzegovina")
            c.country = "Bosnia and Herz"
            if (c.country === "Central African Republic")
            c.country = "Central African Rep."
            if (c.country === "Congo (Brazzaville)") c.country = "Congo"
            if (c.country === "Congo (Kinshasa)") c.country = "Dem. Rep. Congo"
            if (c.country === "Equatorial Guinea") c.country = "Eq. Guinea"
            if (c.country === `Cote d'Ivoire`) c.country = `Côte d'Ivoire`
            this.chartData.push({
            name: c.country,
            value: Number(c.latest.confirmed)
            })
        })
        this.myChartOption.series[0].data = this.chartData
        this.loadChart()
      })
    },
    //加载chart
    loadChart() {
      var promise = new Promise((resolve, reject) => {
        this.$echart.registerMap("world", worldmap)
        this.myChart = this.$echart.init(document.getElementById("chart-view"));
        this.myChart.setOption(this.myChartOption)
        this.myChart.on("selectchanged", (param) => {
          this.chooseCountry(param)
        });
        resolve()
      })
      promise.then(() => {
        this.loading.show = false
        this.loadWorldInfo()
      })
    },
    //选择国家
    chooseCountry(param) {
      if (param.selected.length > 0) {
        this.currentCountry.name = this.countryData[
          param.selected[0].dataIndex[0]
        ].country
        this.currentCountry.confirmed = this.$utils.toThousands(
          this.countryData[param.selected[0].dataIndex[0]].latest.confirmed
        )
        this.currentCountry.deaths = this.$utils.toThousands(
          this.countryData[param.selected[0].dataIndex[0]].latest.deaths
        )
        this.currentCountry.recovered = this.$utils.toThousands(
          this.countryData[param.selected[0].dataIndex[0]].latest.recovered
        )
        this.currentCountry.last_updated = this.fomatTime(
          this.countryData[param.selected[0].dataIndex[0]].last_updated
        )
      } else {
        this.loadWorldInfo()
      }
    },
    //未选中国家时默认绑定全球数据
    loadWorldInfo() {
      this.currentCountry.name = "World";
      this.currentCountry.confirmed = this.$utils.toThousands(
        this.globalData.confirmed
      );
      this.currentCountry.deaths = this.$utils.toThousands(this.globalData.deaths)
      this.currentCountry.recovered = this.$utils.toThousands(
        this.globalData.recovered
      );
      this.currentCountry.last_updated = this.$utils.fomatDateTime(new Date())
    },
    fomatTime (timestr) {
      return this.$utils.fomatDateTime(new Date(timestr.substr(0, timestr.length - 8)))
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  height: calc(100%);
  width: calc(100%);
}
#chart-view {
  height: calc(100%);
  width: calc(100%);
}
.country-info {
  position: absolute;
  z-index: 960;
  left: 70px;
  bottom: 150px;
  width: 300px;
  height: 250px;
  font-size: 14px;
  color: rgb(212, 208, 208);
  span {
    display: block;
    float: left;
    width: 100%;
    margin-bottom: 10px;
  }
  .country-name {
    color: #fff;
    font-size: 20px;
  }
}

</style>